<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>AI信息统计 - n8n工作流监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .back-btn {
            background: white;
            color: #667eea;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            text-decoration: none;
            display: inline-block;
        }
        
        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .main-section {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        /* 日期选择器样式 */
        .date-selector-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 15px;
            margin: 20px 0;
            border: 2px solid #e5e7eb;
        }
        
        .date-selector-group {
            margin: 15px 0;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .date-selector-group label {
            font-size: 1em;
            font-weight: 500;
            color: #333;
            min-width: 100px;
        }
        
        .date-selector-group select {
            flex: 1;
            padding: 10px 15px;
            border-radius: 8px;
            border: 2px solid #667eea;
            font-size: 1em;
            color: #667eea;
            cursor: pointer;
            min-width: 200px;
        }
        
        .date-range-group {
            margin: 15px 0;
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .date-input-wrapper {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            min-width: 250px;
        }
        
        .date-input-wrapper label {
            font-size: 1em;
            font-weight: 500;
            color: #333;
            min-width: 80px;
        }
        
        .date-input-wrapper input[type="date"] {
            flex: 1;
            padding: 10px 15px;
            border-radius: 8px;
            border: 2px solid #667eea;
            font-size: 1em;
            color: #667eea;
            cursor: pointer;
        }
        
        .quick-buttons {
            margin-top: 15px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .quick-btn {
            padding: 8px 20px;
            border-radius: 20px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .quick-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .quick-btn:active {
            transform: translateY(0);
        }
        
        .message-limit {
            margin: 30px auto;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
        }
        
        .message-limit label {
            font-size: 1.1em;
            font-weight: 500;
            color: #333;
        }
        
        .message-limit select {
            padding: 12px 20px;
            border-radius: 25px;
            border: 2px solid #667eea;
            font-size: 1.1em;
            font-weight: bold;
            color: #667eea;
            cursor: pointer;
        }
        
        .evaluate-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 20px 50px;
            border-radius: 50px;
            font-size: 1.3em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            margin: 30px auto;
            display: inline-block;
        }
        
        .evaluate-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 25px rgba(0,0,0,0.3);
        }
        
        .evaluate-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .progress-section {
            display: none;
            margin: 30px 0;
        }
        
        .progress-bar {
            width: 100%;
            height: 30px;
            background: #e9ecef;
            border-radius: 15px;
            overflow: hidden;
            margin-bottom: 15px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .progress-text {
            text-align: center;
            color: #666;
            font-size: 1.1em;
            margin-top: 10px;
        }
        
        .stats-section {
            display: none;
            margin: 30px 0;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        
        .stat-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-card .label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stat-card .value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-card.warning .value {
            color: #f59e0b;
        }
        
        .stat-card.success .value {
            color: #10b981;
        }
        
        .action-buttons {
            display: none;
            margin: 30px 0;
            gap: 20px;
            justify-content: center;
        }
        
        .action-btn {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
            padding: 15px 40px;
            border-radius: 25px;
            font-size: 1.1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }
        
        .action-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .users-section, .messages-section {
            display: none;
            margin-top: 30px;
        }
        
        .section-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 20px;
            text-align: left;
        }
        
        .user-list {
            display: grid;
            gap: 15px;
        }
        
        .user-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
            text-align: left;
        }
        
        .user-item:hover {
            border-color: #667eea;
            transform: translateX(5px);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .user-name {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        
        .user-stats {
            font-size: 0.9em;
            color: #666;
        }
        
        .messages-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }
        
        .message-column {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
        }
        
        .column-title {
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: left;
        }
        
        .salary-related {
            color: #8b5cf6;
        }
        
        .photo-related {
            color: #f59e0b;
        }
        
        .non-salary-related {
            color: #10b981;
        }
        
        .message-item {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
        }
        
        .message-item.salary {
            border-left-color: #8b5cf6;
        }
        
        .message-item.photo {
            border-left-color: #f59e0b;
        }
        
        .message-item.non-salary {
            border-left-color: #10b981;
        }
        
        .message-content {
            font-size: 0.95em;
            color: #333;
            margin-bottom: 10px;
            word-break: break-all;
        }
        
        .message-meta {
            font-size: 0.85em;
            color: #666;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #e9ecef;
        }
        
        .message-timestamp {
            font-size: 0.8em;
            color: #999;
            margin-top: 5px;
            font-style: italic;
        }
        
        .message-timestamp::before {
            content: "🕒 ";
        }
        
        .loading {
            text-align: center;
            color: #666;
            padding: 40px;
            font-size: 1.2em;
        }
        
        .error {
            text-align: center;
            color: #ef4444;
            padding: 40px;
            font-size: 1.2em;
        }
        
        /* 搜索框样式 */
        .search-container {
            position: sticky;
            top: 0;
            z-index: 100;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            border: 2px solid #e5e7eb;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .search-box {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .search-input-wrapper {
            flex: 1;
            min-width: 300px;
            position: relative;
        }
        
        .search-input {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid #667eea;
            border-radius: 25px;
            font-size: 1em;
            outline: none;
            transition: all 0.3s;
        }
        
        .search-input:focus {
            border-color: #764ba2;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #667eea;
            font-size: 1.2em;
        }
        
        .search-stats {
            color: #667eea;
            font-weight: 600;
            font-size: 0.95em;
            padding: 8px 20px;
            background: white;
            border-radius: 20px;
            border: 2px solid #667eea;
        }
        
        .clear-search-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(239, 68, 68, 0.3);
        }
        
        .clear-search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(239, 68, 68, 0.4);
        }
        
        .clear-search-btn:disabled {
            background: #d1d5db;
            cursor: not-allowed;
            box-shadow: none;
            transform: none;
        }
        
        /* 排序按钮样式 */
        .sort-time-btn {
            padding: 10px 25px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(102, 126, 234, 0.3);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .sort-time-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
        }
        
        .sort-time-btn:active {
            transform: translateY(0);
        }
        
        .sort-time-btn .sort-icon {
            font-size: 1.1em;
            transition: transform 0.3s;
        }
        
        .sort-time-btn[data-order="desc"] .sort-icon {
            transform: rotate(180deg);
        }
        
        .message-item.hidden {
            display: none !important;
        }
        
        /* 消息列表容器最小高度，避免晃动 */
        #salaryMessageList, #photoMessageList {
            min-height: 200px;
            transition: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>💰📸 薪资信息和要照片信息统计</h1>
            <p>AI智能评估薪资信息和要照片信息</p>
            <a href="index.html" class="back-btn">← 返回主页</a>
        </div>
        
        <div class="main-section">
            <h2 id="mainTitle">薪资和要照片信息综合评估</h2>
            <p id="mainDescription" style="color: #666; margin: 20px 0;">点击下方按钮开始AI评估，系统会自动评估所有候选人的薪资和要照片相关消息</p>
            
            <!-- 日期选择器 -->
            <div class="date-selector-section">
                <h3 style="color: #667eea; margin-bottom: 20px;">📅 选择评估时间范围</h3>
                
                <!-- 快捷日期选择 -->
                <div class="date-selector-group">
                    <label for="quickDateSelect">快捷日期选择：</label>
                    <select id="quickDateSelect">
                        <option value="">-- 选择一个日期 --</option>
                        <!-- 动态填充 -->
                    </select>
                </div>
                
                <!-- 自定义日期范围 -->
                <div class="date-range-group">
                    <div class="date-input-wrapper">
                        <label for="startDate">开始日期：</label>
                        <input type="date" id="startDate" />
                    </div>
                    <div class="date-input-wrapper">
                        <label for="endDate">结束日期：</label>
                        <input type="date" id="endDate" />
                    </div>
                </div>
                
                <!-- 快捷按钮 -->
                <div class="quick-buttons">
                    <button class="quick-btn" onclick="selectToday()">今天</button>
                    <button class="quick-btn" onclick="selectYesterday()">昨天</button>
                    <button class="quick-btn" onclick="selectLast3Days()">最近3天</button>
                    <button class="quick-btn" onclick="selectLast7Days()">最近7天</button>
                    <button class="quick-btn" onclick="clearDateSelection()">清除日期</button>
                </div>
            </div>
            
            <!-- 条数选择器 -->
            <div class="message-limit">
                <label for="messageLimit">该范围内评估条数：</label>
                <select id="messageLimit">
                    <option value="0" selected>不限制</option>
                    <option value="10">10条</option>
                    <option value="20">20条</option>
                    <option value="50">50条</option>
                    <option value="100">100条</option>
                </select>
            </div>
            
            <button class="evaluate-btn" id="evaluateBtn" onclick="startEvaluation()">
                🚀 开始评估
            </button>
            
            <!-- 进度条 -->
            <div class="progress-section" id="progressSection">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill">0%</div>
                </div>
                <div class="progress-text" id="progressText">准备中...</div>
            </div>
            
            <!-- 统计结果 -->
            <div class="stats-section" id="statsSection">
                <h3>评估结果统计</h3>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="label">总候选人数</div>
                        <div class="value" id="totalCandidates">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="label">总消息数</div>
                        <div class="value" id="totalMessages">0</div>
                    </div>
                    <div class="stat-card" style="border-left: 4px solid #3b82f6;">
                        <div class="label">🔑 关键词评估</div>
                        <div class="value" id="keywordEvaluatedCount">0</div>
                    </div>
                    <div class="stat-card success">
                        <div class="label">AI评估</div>
                        <div class="value" id="evaluatedCount">0</div>
                    </div>
                    <div class="stat-card warning" style="border-left: 4px solid #8b5cf6;">
                        <div class="label">💰 薪资消息</div>
                        <div class="value" id="salaryMessages">0</div>
                    </div>
                    <div class="stat-card warning" style="border-left: 4px solid #f59e0b;">
                        <div class="label">📸 照片消息</div>
                        <div class="value" id="photoMessages">0</div>
                    </div>
                    <div class="stat-card success">
                        <div class="label">📋 其他消息</div>
                        <div class="value" id="nonSalaryMessages">0</div>
                        <div class="sub-info" id="otherMessagesDetail" style="font-size: 0.75em; color: #999; margin-top: 8px;">
                            <!-- 动态显示详细说明 -->
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons" id="actionButtons" style="display: none; flex-wrap: wrap; justify-content: center; gap: 20px;">
                <button class="action-btn" onclick="showMessages()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-color: #667eea;">
                    📋 查看消息列表
                </button>
                <button class="action-btn" onclick="exportResults()" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-color: #10b981;">
                    📥 导出结果
                </button>
            </div>
            
            <!-- 消息分类 -->
            <div class="messages-section" id="messagesSection" style="display: none;">
                <h3 class="section-title">📨 薪资和要照片消息列表</h3>
                
                <!-- 搜索框区域 -->
                <div class="search-container">
                    <div class="search-box">
                        <div class="search-input-wrapper">
                            <input 
                                type="text" 
                                id="messageSearchInput" 
                                class="search-input" 
                                placeholder="🔍 输入关键词搜索候选人姓名或消息内容..."
                                oninput="debouncedFilterMessages()"
                                autocomplete="off"
                            />
                            <span class="search-icon">🔍</span>
                        </div>
                        <div class="search-stats" id="searchStats">
                            显示全部消息
                        </div>
                        <button 
                            class="sort-time-btn" 
                            id="sortTimeBtn"
                            onclick="toggleSortOrder()"
                            data-order="desc"
                            title="点击切换时间排序"
                        >
                            <span class="sort-icon">⬇</span>
                            <span id="sortTimeText">时间降序</span>
                        </button>
                        <button 
                            class="clear-search-btn" 
                            id="clearSearchBtn"
                            onclick="clearSearch()"
                            disabled
                        >
                            ✕ 清除搜索
                        </button>
                    </div>
                </div>
                
                <div class="messages-grid">
                    <div class="message-column">
                        <div class="column-title salary-related" id="salaryColumnTitle">💰 薪资相关消息</div>
                        <div id="salaryMessageList"></div>
                    </div>
                    <div class="message-column">
                        <div class="column-title photo-related" id="photoColumnTitle">📸 要照片相关消息</div>
                        <div id="photoMessageList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let evaluationData = null;
        
        // 🔥 新增：搜索和排序相关变量
        let allDisplayedMessages = []; // 保存所有当前显示的消息元素
        let totalMessageCount = 0; // 总消息数
        let searchDebounceTimer = null; // 防抖定时器
        let currentSortOrder = 'desc'; // 当前排序顺序: 'asc'升序(早到晚), 'desc'降序(晚到早)
        let originalSalaryMessages = []; // 保存原始薪资消息数据用于排序
        let originalPhotoMessages = []; // 保存原始照片消息数据用于排序
        
        // 时间格式化函数
        function formatTimestamp(timestamp) {
            if (!timestamp) {
                console.log('[时间格式化] 时间戳为空');
                return '时间未知';
            }
            
            try {
                // 支持多种时间格式
                let date;
                if (timestamp instanceof Date) {
                    date = timestamp;
                } else if (typeof timestamp === 'string') {
                    // 替换空格为T以支持ISO格式
                    const isoFormat = timestamp.replace(' ', 'T');
                    date = new Date(isoFormat);
                } else {
                    date = new Date(timestamp);
                }
                
                // 检查日期是否有效
                if (isNaN(date.getTime())) {
                    console.warn('[时间格式化] 无效的时间戳:', timestamp);
                    return timestamp; // 返回原始值
                }
                
                // 格式化为本地时间
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                console.log(`[时间格式化] 原始: ${timestamp} -> 格式化: ${formatted}`);
                return formatted;
            } catch (e) {
                console.error('[时间格式化] 格式化失败:', e, '原始值:', timestamp);
                return timestamp || '时间未知';
            }
        }
        
        // 🔥 新增：加载可用的日期列表
        async function loadAvailableDates() {
            console.log('[日期加载] 开始加载可用日期列表...');
            try {
                const response = await fetch('/api/message-dates');
                const data = await response.json();
                
                console.log('[日期加载] 收到日期数据:', data);
                
                if (data.success && data.dates && data.dates.length > 0) {
                    const quickDateSelect = document.getElementById('quickDateSelect');
                    
                    // 清空现有选项（保留默认提示）
                    quickDateSelect.innerHTML = '<option value="">-- 选择一个日期 --</option>';
                    
                    // 添加日期选项（降序排列，最新的在前）
                    // 注意：dates是对象数组 [{date: 'YYYY-MM-DD', pair_count: int}, ...]
                    data.dates.forEach(dateObj => {
                        const option = document.createElement('option');
                        option.value = dateObj.date;
                        // 显示：日期 (N条消息) - 注意这是AI消息数，不是消息对数
                        option.textContent = `${dateObj.date} (${dateObj.pair_count}条AI消息)`;
                        quickDateSelect.appendChild(option);
                    });
                    
                    console.log(`[日期加载] 已加载 ${data.dates.length} 个日期到快捷选择下拉框`);
                    
                    // 监听快捷日期选择
                    quickDateSelect.addEventListener('change', function() {
                        const selectedDate = this.value;
                        if (selectedDate) {
                            console.log(`[快捷选择] 选择日期: ${selectedDate}`);
                            document.getElementById('startDate').value = selectedDate;
                            document.getElementById('endDate').value = selectedDate;
                        }
                    });
                } else {
                    console.warn('[日期加载] 没有可用的日期数据');
                }
            } catch (error) {
                console.error('[日期加载] 加载日期列表失败:', error);
            }
        }
        
        // 选择今天
        function selectToday() {
            const today = new Date().toISOString().split('T')[0];
            console.log('[快捷按钮] 选择今天:', today);
            document.getElementById('startDate').value = today;
            document.getElementById('endDate').value = today;
        }
        
        // 选择昨天
        function selectYesterday() {
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            const dateStr = yesterday.toISOString().split('T')[0];
            console.log('[快捷按钮] 选择昨天:', dateStr);
            document.getElementById('startDate').value = dateStr;
            document.getElementById('endDate').value = dateStr;
        }
        
        // 选择最近3天
        function selectLast3Days() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 2);  // 今天算1天，所以-2
            
            const startDateStr = startDate.toISOString().split('T')[0];
            const endDateStr = endDate.toISOString().split('T')[0];
            console.log('[快捷按钮] 选择最近3天:', startDateStr, '~', endDateStr);
            document.getElementById('startDate').value = startDateStr;
            document.getElementById('endDate').value = endDateStr;
        }
        
        // 选择最近7天
        function selectLast7Days() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 6);  // 今天算1天，所以-6
            
            const startDateStr = startDate.toISOString().split('T')[0];
            const endDateStr = endDate.toISOString().split('T')[0];
            console.log('[快捷按钮] 选择最近7天:', startDateStr, '~', endDateStr);
            document.getElementById('startDate').value = startDateStr;
            document.getElementById('endDate').value = endDateStr;
        }
        
        // 清除日期选择
        function clearDateSelection() {
            console.log('[快捷按钮] 清除日期选择');
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
            document.getElementById('quickDateSelect').value = '';
        }
        
        // 页面加载时检测是否有评估数据
        window.addEventListener('DOMContentLoaded', async function() {
            console.log('========== 页面加载开始 ==========');
            console.log('检测是否有已保存的评估数据...');
            
            // 🔥 新增：加载可用日期列表
            await loadAvailableDates();
            
            await checkAndLoadExistingEvaluation();
        });
        
        // 检测并加载已有评估数据
        async function checkAndLoadExistingEvaluation() {
            try {
                console.log('调用 /api/evaluation-statistics API...');
                const response = await fetch('/api/evaluation-statistics');
                
                if (!response.ok) {
                    console.log('API调用失败:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('API返回数据:', data);
                
                if (data.has_data) {
                    console.log('找到已保存的评估数据');
                    console.log('评估时间:', data.timestamp);
                    console.log('薪资相关消息数:', data.salary_messages_count);
                    console.log('索要照片消息数:', data.photo_messages_count);
                    
                    // 加载评估数据
                    await loadEvaluationData(data);
                } else {
                    console.log('暂无已保存的评估数据');
                }
            } catch (error) {
                console.error('检测评估数据时发生错误:', error);
            }
        }
        
        // 加载评估数据
        async function loadEvaluationData(statistics) {
            try {
                console.log('========== [薪资和要照片统计] 开始加载评估数据 ==========');
                console.log('[薪资和要照片统计] 接收到的统计数据:', statistics);
                
                // 修改：保留开始评估按钮和选择器，只更新标题和描述
                const mainTitle = document.getElementById('mainTitle');
                const mainDescription = document.getElementById('mainDescription');
                const evaluateBtn = document.getElementById('evaluateBtn');
                const messageLimitSelect = document.getElementById('messageLimit');
                
                console.log('[薪资和要照片统计] mainTitle元素:', mainTitle);
                console.log('[薪资和要照片统计] mainTitle当前文本内容:', mainTitle ? mainTitle.textContent : 'null');
                console.log('[薪资和要照片统计] 准备更新主标题为: 历史评估结果');
                
                if (mainTitle) {
                    const oldText = mainTitle.textContent;
                    mainTitle.textContent = '历史评估结果';
                    const newText = mainTitle.textContent;
                    console.log('[薪资和要照片统计] 主标题更新: [' + oldText + '] -> [' + newText + ']');
                    console.log('[薪资和要照片统计] 主标题更新成功');
                } else {
                    console.error('[薪资和要照片统计] 错误：mainTitle元素不存在');
                }
                
                if (mainDescription) {
                    mainDescription.textContent = '查看历史评估结果或继续进行新的评估';
                    console.log('[薪资和要照片统计] 已更新描述文字');
                }
                
                // 确保评估按钮始终可见且可用
                if (evaluateBtn) {
                    evaluateBtn.style.display = 'block';
                    evaluateBtn.disabled = false;
                    evaluateBtn.textContent = '🚀 开始评估';
                    console.log('[薪资和要照片统计] 已确保评估按钮可见且可用');
                }
                
                // 确保消息条数选择器可见
                if (messageLimitSelect && messageLimitSelect.parentElement) {
                    messageLimitSelect.parentElement.style.display = 'flex';
                    console.log('[薪资和要照片统计] 已确保消息条数选择器可见');
                }
                
                // 显示统计结果
                displayStats(statistics);
                console.log('[薪资和要照片统计] 已显示统计结果');
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                console.log('[薪资和要照片统计] 已显示操作按钮');
                
                // 构建evaluationData对象 - 使用statistics中的完整数据
                if (statistics.data && typeof statistics.data === 'object') {
                    evaluationData = statistics.data;
                    console.log('[薪资和要照片统计] 使用完整的评估数据');
                    console.log('[薪资和要照片统计] 包含all_evaluations:', !!evaluationData.all_evaluations);
                    if (evaluationData.all_evaluations) {
                        console.log('[薪资和要照片统计] all_evaluations长度:', evaluationData.all_evaluations.length);
                    }
                } else {
                    // 如果没有完整数据，只构建统计对象
                    evaluationData = {
                        success: true,
                        total_candidates: statistics.total_candidates || 0,
                        total_messages: statistics.total_messages || 0,
                        total_ai_messages: statistics.total_ai_messages || 0,
                        evaluated_count: statistics.evaluated_count || 0,
                        failed_count: statistics.failed_count || 0,
                        pending_count: statistics.pending_count || 0,
                        salary_messages_count: statistics.salary_messages_count || 0,
                        photo_messages_count: statistics.photo_messages_count || 0,
                        non_salary_messages_count: statistics.non_salary_messages_count || 0,
                        timestamp: statistics.timestamp,
                        all_evaluations: []
                    };
                    console.log('[薪资和要照片统计] 构建基础统计数据');
                    console.log('[薪资和要照片统计] 薪资消息:', evaluationData.salary_messages_count, '要照片消息:', evaluationData.photo_messages_count);
                }
                
                console.log('========== [薪资和要照片统计] 评估数据加载完成 ==========');
                
            } catch (error) {
                console.error('[薪资和要照片统计] 加载评估数据时发生错误:', error);
                console.error('[薪资和要照片统计] 错误堆栈:', error.stack);
            }
        }
        
        // 开始评估
        async function startEvaluation() {
            console.log('[薪资和要照片统计] 开始评估流程');
            const btn = document.getElementById('evaluateBtn');
            btn.disabled = true;
            btn.textContent = '评估中...';
            
            // 显示进度条
            document.getElementById('progressSection').style.display = 'block';
            
            try {
                // 获取选择的消息条数
                const messageLimit = parseInt(document.getElementById('messageLimit').value);
                console.log(`[薪资和要照片统计] 获取消息条数限制: ${messageLimit}`);
                
                // 🔥 新增：获取日期选择
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                
                console.log(`[薪资和要照片统计] 开始日期: ${startDate || '不限制'}`);
                console.log(`[薪资和要照片统计] 结束日期: ${endDate || '不限制'}`);
                
                // 调用后端API进行实时评估
                updateProgress(10, '正在连接服务器...');
                
                const apiUrl = `/api/batch-evaluate`;
                const requestBody = {
                    limit: messageLimit
                };
                
                // 🔥 新增：添加日期参数
                if (startDate) {
                    requestBody.start_date = startDate;
                    console.log(`[薪资和要照片统计] 添加开始日期参数: ${startDate}`);
                }
                if (endDate) {
                    requestBody.end_date = endDate;
                    console.log(`[薪资和要照片统计] 添加结束日期参数: ${endDate}`);
                }
                
                console.log(`[薪资和要照片统计] 请求体:`, requestBody);
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                console.log(`[薪资和要照片统计] 收到响应，状态码: ${response.status}`);
                if (!response.ok) {
                    console.error(`[薪资和要照片统计] 服务器返回错误: ${response.status} ${response.statusText}`);
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }
                
                updateProgress(30, '开始评估消息...');
                
                const data = await response.json();
                
                if (!data.success) {
                    console.error(`[薪资和要照片统计] 评估失败: ${data.error || '未知错误'}`);
                    throw new Error(data.error || '评估失败');
                }
                
                // 模拟进度更新（因为后端是同步的，我们无法获取实时进度）
                updateProgress(50, '评估进行中...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                updateProgress(70, '正在整理结果...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                updateProgress(90, '即将完成...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                // 保存完整的评估数据
                evaluationData = data;
                console.log('[薪资和要照片统计] 评估数据已保存');
                
                updateProgress(100, '评估完成！');
                
                // 显示统计结果
                displayStats(data);
                console.log('[薪资和要照片统计] 统计结果显示完成');
                
                // 显示操作按钮
                document.getElementById('actionButtons').style.display = 'flex';
                console.log('[薪资和要照片统计] 操作按钮显示完成');
                
                // 不自动显示消息分类，等待用户点击"查看消息列表"按钮
                
                // 保持按钮可点击状态
                btn.disabled = false;
                btn.textContent = '🚀 重新开始评估';
                console.log('[薪资和要照片统计] 评估按钮已重置，可以继续评估');
                
            } catch (error) {
                console.error('[薪资和要照片统计] 评估过程中发生错误', error);
                console.error('[薪资和要照片统计] 错误堆栈:', error.stack);
                alert(`评估失败: ${error.message}`);
                btn.disabled = false;
                btn.textContent = '🚀 开始评估';
                document.getElementById('progressSection').style.display = 'none';
            }
        }
        
        // 过滤消息
        function filterMessages(data, limit) {
            // 深拷贝数据
            const filteredData = JSON.parse(JSON.stringify(data));
            
            // 过滤AI薪资分析数据
            if (filteredData.ai_salary_analysis) {
                const allMessages = [
                    ...(filteredData.ai_salary_analysis.all_salary_messages || []),
                    ...(filteredData.ai_salary_analysis.all_non_salary_messages || [])
                ];
                
                // 按时间排序（最新的在前）
                allMessages.sort((a, b) => {
                    const timeA = new Date(a.created_at || 0);
                    const timeB = new Date(b.created_at || 0);
                    return timeB - timeA;
                });
                
                // 取最近的N条
                const limitedMessages = allMessages.slice(0, limit);
                
                // 重新分类
                const salaryMessages = limitedMessages.filter(msg => 
                    msg.evaluation && msg.evaluation.is_salary_related
                );
                const nonSalaryMessages = limitedMessages.filter(msg => 
                    msg.evaluation && !msg.evaluation.is_salary_related
                );
                
                // 更新数据
                filteredData.ai_salary_analysis.all_salary_messages = salaryMessages;
                filteredData.ai_salary_analysis.all_non_salary_messages = nonSalaryMessages;
                filteredData.ai_salary_analysis.total_salary_messages = salaryMessages.length;
                filteredData.ai_salary_analysis.total_non_salary_messages = nonSalaryMessages.length;
                filteredData.ai_salary_analysis.total_messages = limitedMessages.length;
                filteredData.ai_salary_analysis.overall_salary_rate = 
                    limitedMessages.length > 0 ? 
                    (salaryMessages.length / limitedMessages.length * 100) : 0;
                
                // 更新summary
                if (filteredData.summary) {
                    filteredData.summary.salary_mentions = salaryMessages.length;
                    filteredData.summary.salary_rate = 
                        limitedMessages.length > 0 ?
                        ((salaryMessages.length / limitedMessages.length) * 100).toFixed(2) + '%' : '0.00%';
                }
            }
            
            return filteredData;
        }
        
        // 更新进度
        function updateProgress(percent, text) {
            document.getElementById('progressFill').style.width = percent + '%';
            document.getElementById('progressFill').textContent = percent + '%';
            document.getElementById('progressText').textContent = text;
        }
        
        // 显示统计
        function displayStats(data) {
            // DEBUG: 打印接收到的数据
            console.log('========== 前端接收数据 ==========');
            console.log('完整数据:', data);
            console.log('总候选人数:', data.total_candidates);
            console.log('总消息数(AI评估):', data.total_messages);
            console.log('总AI消息数:', data.total_ai_messages);
            console.log('AI评估数:', data.evaluated_count);
            console.log('薪资相关消息数:', data.salary_messages_count);
            console.log('照片相关消息数:', data.photo_messages_count);
            console.log('其他消息数:', data.non_salary_messages_count);
            console.log('评估数据总数:', data.all_evaluations?.length);
            console.log('==================================');
            
            // 支持新的API响应格式
            const totalCandidates = data.total_candidates || 0;
            const totalAIMessages = data.total_ai_messages || 0; // 所有AI消息数
            const totalMessages = data.total_messages || 0; // 已评估的消息数
            const keywordEvaluatedCount = data.keyword_evaluated_count || 0; // 🔥 关键词评估通过数量
            const evaluatedCount = data.evaluated_count || 0;
            const salaryMessagesCount = data.salary_messages_count || 0;
            const photoMessagesCount = data.photo_messages_count || 0;
            const nonSalaryMessagesCount = data.non_salary_messages_count || 0;
            
            // 🔥 新增：计算误匹配和普通消息
            // AI信息统计页面（综合）：误匹配 = 关键词评估 - 薪资 - 照片
            const mismatchedCount = keywordEvaluatedCount - salaryMessagesCount - photoMessagesCount;
            // 普通消息 = 总消息 - 关键词评估（关键词未通过）
            const normalCount = totalAIMessages - keywordEvaluatedCount;
            
            console.log('[统计显示] 误匹配消息:', mismatchedCount);
            console.log('[统计显示] 普通消息:', normalCount);
            console.log('[统计显示] 其他消息总数:', nonSalaryMessagesCount);
            console.log('[统计显示] 验证: 误匹配 + 普通 = 其他:', mismatchedCount + normalCount, '=', nonSalaryMessagesCount);
            
            // 显示所有统计信息
            document.getElementById('totalCandidates').textContent = totalCandidates;
            document.getElementById('totalMessages').textContent = totalAIMessages; // 显示总AI消息数
            document.getElementById('keywordEvaluatedCount').textContent = keywordEvaluatedCount; // 🔥 关键词评估数
            document.getElementById('evaluatedCount').textContent = evaluatedCount; // AI评估数
            document.getElementById('salaryMessages').textContent = salaryMessagesCount;
            document.getElementById('photoMessages').textContent = photoMessagesCount;
            document.getElementById('nonSalaryMessages').textContent = nonSalaryMessagesCount;
            
            // 🔥 新增：显示其他消息的详细说明
            const otherMessagesDetail = document.getElementById('otherMessagesDetail');
            if (otherMessagesDetail) {
                otherMessagesDetail.textContent = `${mismatchedCount}条误匹配 + ${normalCount}条普通消息`;
                console.log('[统计显示] 其他消息详细说明已更新');
            }
            
            document.getElementById('statsSection').style.display = 'block';
        }
        
        // 显示消息分类
        function showMessages() {
            console.log('========== [薪资和照片页面] 开始显示消息列表 ==========');
            
            // 显示消息列表区域
            const messagesSection = document.getElementById('messagesSection');
            messagesSection.style.display = 'block';
            
            const salaryList = document.getElementById('salaryMessageList');
            const photoList = document.getElementById('photoMessageList');
            
            salaryList.innerHTML = '';
            photoList.innerHTML = '';
            
            if (!evaluationData) {
                console.log('[薪资和照片页面] evaluationData为空，显示暂无数据');
                salaryList.innerHTML = '<div class="loading">暂无消息数据</div>';
                photoList.innerHTML = '<div class="loading">暂无消息数据</div>';
                return;
            }
            
            // 从all_evaluations过滤薪资和照片相关消息
            const allEvaluations = evaluationData.all_evaluations || [];
            console.log('[薪资和照片页面] 所有评估数据:', allEvaluations.length);
            
            const salaryMessages = [];
            const photoMessages = [];
            
            allEvaluations.forEach(msg => {
                const evaluation = msg.evaluation || {};
                const isSalary = evaluation.is_salary_related || false;
                const isPhoto = evaluation.is_photo_request || false;
                
                if (isSalary) {
                    salaryMessages.push(msg);
                    console.log(`[薪资和照片页面] 发现薪资消息 - ID: ${msg.message_id || msg.id}, 内容预览: ${(msg.content || '').substring(0, 20)}...`);
                }
                
                if (isPhoto) {
                    photoMessages.push(msg);
                    console.log(`[薪资和照片页面] 发现照片消息 - ID: ${msg.message_id || msg.id}, 内容预览: ${(msg.content || '').substring(0, 20)}...`);
                }
            });
            
            console.log(`[薪资和照片页面] 薪资相关消息数: ${salaryMessages.length}`);
            console.log(`[薪资和照片页面] 要照片相关消息数: ${photoMessages.length}`);
            
            // 更新列标题显示数量
            document.getElementById('salaryColumnTitle').textContent = `💰 薪资相关消息 (${salaryMessages.length})`;
            document.getElementById('photoColumnTitle').textContent = `📸 要照片相关消息 (${photoMessages.length})`;
            
            // 显示薪资相关消息
            console.log('[薪资和照片页面] 开始渲染薪资消息列表...');
            salaryMessages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item salary';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.salary_score || evaluation.score || 0;
                const reason = evaluation.salary_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                console.log(`[薪资消息 #${index + 1}] 候选人: ${candidateName}, 评分: ${score}, 时间: ${timestamp}`);
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                // 为按钮添加点击事件监听器
                const salaryBtn = messageItem.querySelector('.view-chat-btn');
                if (salaryBtn) {
                    salaryBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                salaryList.appendChild(messageItem);
            });
            
            if (salaryList.children.length === 0) {
                salaryList.innerHTML = '<div class="loading">暂无薪资相关消息</div>';
                console.log('[薪资和照片页面] 薪资列表为空');
            }
            
            // 显示要照片相关消息
            console.log('[薪资和照片页面] 开始渲染照片消息列表...');
            photoMessages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item photo';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.photo_score || evaluation.score || 0;
                const reason = evaluation.photo_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                console.log(`[照片消息 #${index + 1}] 候选人: ${candidateName}, 评分: ${score}, 时间: ${timestamp}`);
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                // 为按钮添加点击事件监听器
                const photoBtn = messageItem.querySelector('.view-chat-btn');
                if (photoBtn) {
                    photoBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                photoList.appendChild(messageItem);
            });
            
            if (photoList.children.length === 0) {
                photoList.innerHTML = '<div class="loading">暂无要照片相关消息</div>';
                console.log('[薪资和照片页面] 照片列表为空');
            }
            
            console.log('========== [薪资和照片页面] 消息列表显示完成 ==========');
            console.log(`[薪资和照片页面] 总结: 显示了${salaryMessages.length}条薪资消息，${photoMessages.length}条照片消息`);
            
            // 🔥 新增：保存所有消息元素供搜索使用
            allDisplayedMessages = document.querySelectorAll('.message-item');
            totalMessageCount = allDisplayedMessages.length;
            
            // 保存原始消息数据用于排序
            originalSalaryMessages = salaryMessages;
            originalPhotoMessages = photoMessages;
            
            console.log(`[薪资和照片页面] 已保存 ${allDisplayedMessages.length} 个消息元素供搜索使用`);
            
            // 重置搜索框
            const searchInput = document.getElementById('messageSearchInput');
            if (searchInput) {
                searchInput.value = '';
            }
            updateSearchStats(totalMessageCount, totalMessageCount);
            const clearBtn = document.getElementById('clearSearchBtn');
            if (clearBtn) {
                clearBtn.disabled = true;
            }
            
            console.log(`[薪资和照片页面] 搜索功能已初始化，总消息数: ${totalMessageCount}`);
        }
        
        // 导出评估结果
        async function exportResults() {
            console.log('========== 开始导出 ==========');
            console.log('evaluationData存在:', !!evaluationData);
            console.log('evaluationData完整内容:', JSON.stringify(evaluationData, null, 2));
            
            if (!evaluationData) {
                console.log('错误: evaluationData为空');
                alert('请先进行评估');
                return;
            }
            
            try {
                // 获取所有评估数据
                const allEvaluations = evaluationData.all_evaluations || [];
                
                console.log('========== 导出数据调试 ==========');
                console.log('all_evaluations长度:', allEvaluations.length);
                console.log('evaluationData的所有键:', Object.keys(evaluationData));
                console.log('all_evaluations前3条数据:', allEvaluations.slice(0, 3));
                console.log('数据类型检查:');
                console.log('- allEvaluations是数组:', Array.isArray(allEvaluations));
                console.log('- 第一条数据:', allEvaluations[0]);
                if (allEvaluations.length > 0) {
                    console.log('- 第一条数据的键:', Object.keys(allEvaluations[0]));
                }
                console.log('==================================');
                
                if (allEvaluations.length === 0) {
                    console.log('错误: all_evaluations为空');
                    console.log('尝试查找其他可能的评估数据字段...');
                    
                    // 检查是否有其他字段包含评估数据
                    if (evaluationData.salary_messages) {
                        console.log('找到 salary_messages:', evaluationData.salary_messages.length);
                    }
                    if (evaluationData.non_salary_messages) {
                        console.log('找到 non_salary_messages:', evaluationData.non_salary_messages.length);
                    }
                    
                    alert('没有可导出的评估数据。请确保评估成功完成。');
                    return;
                }
                
                console.log('准备发送导出请求...');
                
                // 准备请求数据
                const requestData = {
                    evaluations: allEvaluations
                };
                
                console.log('========== 发送的请求数据 ==========');
                console.log('请求数据对象:', requestData);
                console.log('请求数据长度:', JSON.stringify(requestData).length, 'bytes');
                console.log('评估数据样本（前2条）:');
                if (allEvaluations.length > 0) {
                    console.log(JSON.stringify(allEvaluations[0], null, 2));
                }
                if (allEvaluations.length > 1) {
                    console.log(JSON.stringify(allEvaluations[1], null, 2));
                }
                console.log('=====================================');
                
                // 调用导出API
                const response = await fetch('/api/export-evaluations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });
                
                console.log('导出API响应状态:', response.status);
                console.log('导出API响应头:', [...response.headers.entries()]);
                
                if (!response.ok) {
                    throw new Error(`导出失败: ${response.statusText}`);
                }
                
                const result = await response.json();
                console.log('导出结果:', result);
                
                if (result.success) {
                    alert(`成功导出 ${result.exported_count} 条评估结果到:\n${result.db_path}`);
                } else {
                    alert('导出失败');
                }
            } catch (error) {
                console.error('导出错误详情:', error);
                console.error('错误堆栈:', error.stack);
                alert(`导出失败: ${error.message}`);
            }
        }
        
        /**
         * 查看聊天历史记录
         */
        function viewChatHistory(candidateId, candidateName) {
            console.log('[查看聊天] ========== 准备查看聊天记录 ==========');
            console.log('[查看聊天] 候选人ID:', candidateId);
            console.log('[查看聊天] 候选人姓名:', candidateName);
            
            if (!candidateId) {
                console.error('[查看聊天] 候选人ID为空');
                alert('无法获取候选人信息');
                return;
            }
            
            // 构建目标URL，包含from参数以便返回
            const currentPage = 'photo_detail.html';
            const targetUrl = `user_chat.html?candidate_id=${candidateId}&from=${encodeURIComponent(currentPage)}`;
            
            console.log('[查看聊天] 目标URL:', targetUrl);
            console.log('[查看聊天] 跳转到聊天记录页面...');
            
            // 跳转到聊天记录页面
            window.location.href = targetUrl;
        }
        
        /**
         * 🔥 新增：防抖处理的搜索函数
         */
        function debouncedFilterMessages() {
            console.log('[搜索过滤] 触发防抖搜索');
            
            // 清除之前的定时器
            if (searchDebounceTimer) {
                clearTimeout(searchDebounceTimer);
            }
            
            // 设置新的定时器，300ms后执行搜索
            searchDebounceTimer = setTimeout(() => {
                console.log('[搜索过滤] 执行搜索');
                filterMessages();
            }, 300);
        }
        
        /**
         * 🔥 新增：搜索过滤功能
         * 实时过滤消息列表
         */
        function filterMessages() {
            console.log('========== [搜索过滤] 开始过滤消息 ==========');
            
            // 安全性检查
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            if (!allDisplayedMessages || allDisplayedMessages.length === 0) {
                console.warn('[搜索过滤] ⚠️ 没有可搜索的消息');
                return;
            }
            
            const searchTerm = searchInput.value.trim().toLowerCase();
            
            console.log(`[搜索过滤] 搜索关键词: "${searchTerm}"`);
            console.log(`[搜索过滤] 总消息数: ${totalMessageCount}`);
            
            // 如果搜索词为空，显示所有消息
            if (!searchTerm) {
                console.log('[搜索过滤] 搜索词为空，显示所有消息');
                allDisplayedMessages.forEach(item => {
                    if (item && item.classList) {
                        item.classList.remove('hidden');
                    }
                });
                updateSearchStats(totalMessageCount, totalMessageCount);
                const clearBtn = document.getElementById('clearSearchBtn');
                if (clearBtn) clearBtn.disabled = true;
                console.log(`[搜索过滤] ✅ 已显示全部 ${totalMessageCount} 条消息`);
                return;
            }
            
            // 启用清除按钮
            const clearBtn = document.getElementById('clearSearchBtn');
            if (clearBtn) clearBtn.disabled = false;
            
            let visibleCount = 0;
            let hiddenCount = 0;
            
            // 使用requestAnimationFrame优化性能
            requestAnimationFrame(() => {
                // 遍历所有消息元素进行过滤
                allDisplayedMessages.forEach((item, index) => {
                    if (!item || !item.classList) {
                        console.warn(`[搜索过滤] ⚠️ 消息元素 #${index} 无效`);
                        return;
                    }
                    
                    try {
                        // 获取消息卡片中的关键文本内容
                        // 搜索：消息内容和候选人相关信息
                        const messageContent = item.querySelector('.message-content')?.textContent.toLowerCase() || '';
                        const messageMeta = item.querySelector('.message-meta')?.textContent.toLowerCase() || '';
                        
                        // 组合可搜索的文本
                        const searchableText = `${messageContent} ${messageMeta}`;
                        
                        // 判断是否匹配搜索词
                        const isMatch = searchableText.includes(searchTerm);
                        
                        if (isMatch) {
                            item.classList.remove('hidden');
                            visibleCount++;
                            
                            // 记录匹配详情（仅前3条）
                            if (visibleCount <= 3) {
                                console.log(`[搜索过滤] ✅ 匹配 #${visibleCount}: ${messageContent.substring(0, 30)}...`);
                            }
                        } else {
                            item.classList.add('hidden');
                            hiddenCount++;
                        }
                    } catch (error) {
                        console.error(`[搜索过滤] ❌ 处理消息 #${index} 时出错:`, error);
                    }
                });
                
                // 更新统计信息
                updateSearchStats(visibleCount, totalMessageCount);
                
                console.log('[搜索过滤] ========== 过滤完成 ==========');
                console.log(`[搜索过滤] 📊 统计结果:`);
                console.log(`  - 显示消息: ${visibleCount} 条`);
                console.log(`  - 隐藏消息: ${hiddenCount} 条`);
                console.log(`  - 总消息数: ${totalMessageCount} 条`);
                console.log(`  - 匹配率: ${((visibleCount / totalMessageCount) * 100).toFixed(2)}%`);
                
                // 如果没有匹配结果，给出提示
                if (visibleCount === 0) {
                    console.warn('[搜索过滤] ⚠️ 未找到匹配的消息');
                }
            });
        }
        
        /**
         * 🔥 新增：更新搜索统计信息
         */
        function updateSearchStats(visibleCount, totalCount) {
            const searchStats = document.getElementById('searchStats');
            
            if (!searchStats) {
                console.error('[搜索统计] ❌ 统计元素不存在');
                return;
            }
            
            if (visibleCount === totalCount) {
                searchStats.textContent = `显示全部消息 (${totalCount})`;
                searchStats.style.borderColor = '#667eea';
                searchStats.style.color = '#667eea';
                console.log(`[搜索统计] 显示全部消息: ${totalCount} 条`);
            } else {
                searchStats.textContent = `找到 ${visibleCount} / ${totalCount} 条消息`;
                searchStats.style.borderColor = visibleCount > 0 ? '#10b981' : '#f59e0b';
                searchStats.style.color = visibleCount > 0 ? '#10b981' : '#f59e0b';
                console.log(`[搜索统计] 过滤结果: ${visibleCount} / ${totalCount} 条`);
            }
        }
        
        /**
         * 🔥 新增：清除搜索
         */
        function clearSearch() {
            console.log('[搜索过滤] 清除搜索条件');
            
            const searchInput = document.getElementById('messageSearchInput');
            if (!searchInput) {
                console.error('[搜索过滤] ❌ 搜索框元素不存在');
                return;
            }
            
            searchInput.value = '';
            
            // 直接触发过滤函数（不使用防抖）
            filterMessages();
            
            // 让搜索框失去焦点
            searchInput.blur();
            
            console.log('[搜索过滤] ✅ 搜索已清除，已显示所有消息');
        }
        
        /**
         * 🔥 新增：按时间排序消息
         */
        function sortMessagesByTime(messages, order) {
            console.log(`[时间排序] 开始排序，顺序: ${order}, 消息数: ${messages.length}`);
            
            if (!messages || messages.length === 0) {
                console.warn('[时间排序] ⚠️ 消息列表为空');
                return [];
            }
            
            // 复制数组避免修改原数组
            const sortedMessages = [...messages];
            
            sortedMessages.sort((a, b) => {
                const timeA = new Date(a.created_at || 0).getTime();
                const timeB = new Date(b.created_at || 0).getTime();
                
                if (order === 'asc') {
                    // 升序：早到晚
                    return timeA - timeB;
                } else {
                    // 降序：晚到早
                    return timeB - timeA;
                }
            });
            
            // 打印前3条消息的时间用于验证
            if (sortedMessages.length > 0) {
                console.log('[时间排序] 前3条消息时间:');
                sortedMessages.slice(0, 3).forEach((msg, idx) => {
                    const time = formatTimestamp(msg.created_at);
                    console.log(`  ${idx + 1}. ${time}`);
                });
            }
            
            console.log('[时间排序] ✅ 排序完成');
            return sortedMessages;
        }
        
        /**
         * 🔥 新增：切换排序顺序
         */
        function toggleSortOrder() {
            console.log('========== [时间排序] 切换排序顺序 ==========');
            console.log(`[时间排序] 当前顺序: ${currentSortOrder}`);
            
            // 切换排序顺序
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
            
            console.log(`[时间排序] 新顺序: ${currentSortOrder}`);
            
            // 更新按钮显示
            const sortBtn = document.getElementById('sortTimeBtn');
            const sortText = document.getElementById('sortTimeText');
            
            if (sortBtn && sortText) {
                sortBtn.setAttribute('data-order', currentSortOrder);
                
                if (currentSortOrder === 'asc') {
                    sortText.textContent = '时间升序';
                    sortBtn.title = '当前：早→晚，点击切换';
                    console.log('[时间排序] 按钮更新为：时间升序 ⬆');
                } else {
                    sortText.textContent = '时间降序';
                    sortBtn.title = '当前：晚→早，点击切换';
                    console.log('[时间排序] 按钮更新为：时间降序 ⬇');
                }
            }
            
            // 重新渲染消息列表
            if (originalSalaryMessages.length > 0 || originalPhotoMessages.length > 0) {
                console.log('[时间排序] 重新渲染消息列表...');
                
                // 按新顺序排序薪资和照片消息
                const sortedSalaryMessages = sortMessagesByTime(originalSalaryMessages, currentSortOrder);
                const sortedPhotoMessages = sortMessagesByTime(originalPhotoMessages, currentSortOrder);
                
                // 重新渲染HTML
                rerenderMessages(sortedSalaryMessages, sortedPhotoMessages);
                
                // 如果有搜索条件，重新应用过滤
                const searchInput = document.getElementById('messageSearchInput');
                if (searchInput && searchInput.value.trim()) {
                    console.log('[时间排序] 重新应用搜索过滤...');
                    setTimeout(() => {
                        filterMessages();
                    }, 100);
                }
                
                console.log('[时间排序] ✅ 消息列表重新渲染完成');
            } else {
                console.warn('[时间排序] ⚠️ 没有消息数据可排序');
            }
            
            console.log('[时间排序] ========== 排序切换完成 ==========');
        }
        
        /**
         * 🔥 新增：重新渲染消息列表
         */
        function rerenderMessages(salaryMessages, photoMessages) {
            console.log('[消息渲染] 开始重新渲染消息列表...');
            console.log(`[消息渲染] 薪资消息: ${salaryMessages.length} 条`);
            console.log(`[消息渲染] 照片消息: ${photoMessages.length} 条`);
            
            const salaryList = document.getElementById('salaryMessageList');
            const photoList = document.getElementById('photoMessageList');
            
            salaryList.innerHTML = '';
            photoList.innerHTML = '';
            
            // 渲染薪资消息
            salaryMessages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item salary';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.salary_score || evaluation.score || 0;
                const reason = evaluation.salary_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                // 为按钮添加点击事件监听器
                const salaryBtn = messageItem.querySelector('.view-chat-btn');
                if (salaryBtn) {
                    salaryBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                salaryList.appendChild(messageItem);
            });
            
            if (salaryList.children.length === 0) {
                salaryList.innerHTML = '<div class="loading">暂无薪资相关消息</div>';
            }
            
            // 渲染照片消息
            photoMessages.forEach((msg, index) => {
                const messageItem = document.createElement('div');
                messageItem.className = 'message-item photo';
                
                const evaluation = msg.evaluation || {};
                const content = msg.content || '无内容';
                const candidateName = msg.candidate_name || `#${msg.candidate_id || '未知'}`;
                const score = evaluation.photo_score || evaluation.score || 0;
                const reason = evaluation.photo_reason || evaluation.reason || '无评估理由';
                const timestamp = msg.created_at || '';
                
                messageItem.innerHTML = `
                    <div class="message-content">${content}</div>
                    <div class="message-meta">
                        候选人 ${candidateName} | 
                        评分: ${score}分 | 
                        ${reason}
                        <button class="view-chat-btn" 
                                data-candidate-id="${msg.candidate_id}" 
                                data-candidate-name="${candidateName.replace(/"/g, '&quot;')}"
                                style="margin-left: 15px; padding: 5px 15px; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
                                       color: white; border: none; border-radius: 15px; cursor: pointer; font-size: 0.9em; 
                                       transition: all 0.3s; box-shadow: 0 2px 5px rgba(0,0,0,0.2);"
                                onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 10px rgba(0,0,0,0.3)';"
                                onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 5px rgba(0,0,0,0.2)';">
                            💬 查看聊天记录
                        </button>
                    </div>
                    <div class="message-timestamp">${formatTimestamp(timestamp)}</div>
                `;
                
                // 为按钮添加点击事件监听器
                const photoBtn = messageItem.querySelector('.view-chat-btn');
                if (photoBtn) {
                    photoBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const candidateId = this.getAttribute('data-candidate-id');
                        const candidateName = this.getAttribute('data-candidate-name');
                        viewChatHistory(candidateId, candidateName);
                    });
                }
                
                photoList.appendChild(messageItem);
            });
            
            if (photoList.children.length === 0) {
                photoList.innerHTML = '<div class="loading">暂无要照片相关消息</div>';
            }
            
            // 更新消息元素引用
            allDisplayedMessages = document.querySelectorAll('.message-item');
            totalMessageCount = allDisplayedMessages.length;
            
            console.log(`[消息渲染] ✅ 渲染完成，总消息数: ${totalMessageCount}`);
        }
    </script>
</body>
</html>
